package com.atliuzu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atliuzu.bean.CartAddUuBean;
import com.atliuzu.bean.TradeOrderBean;
import com.atliuzu.utils.ClickHouseUtil;
import com.atliuzu.utils.DateFormatUtil;
import com.atliuzu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 交易域下单各窗口汇总表
 * @Author Administrator
 * @Time 2022-08-20-14:51
 */
public class DwsTradeOrderWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1.创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 1.1 状态后端设置
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                3, Time.days(1), Time.minutes(1)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage(
//                "hdfs://hadoop102:8020/ck"
//        );
//        System.setProperty("HADOOP_USER_NAME", "atguigu");


        //TODO 2.从kafka dwd_trade_order_detail主题读取数据转为流
        DataStreamSource<String> streamSource = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(
                "dwd_trade_order_detail", "group1"));

        //TODO 3.将流转化为json
        SingleOutputStreamOperator<JSONObject> jsonObjDS =
                streamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                out.collect(jsonObject);
            }
        });

        //TODO 4.提取时间戳
        SingleOutputStreamOperator<JSONObject> watermarksDS =
                jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {

                return DateFormatUtil.toTs(element.getString("create_time"), true);
            }
        }));

        //TODO 5.按user_id去重，将去重数据转化为javabean
        KeyedStream<JSONObject, String> keyByDS = watermarksDS.keyBy(json -> json.getString("user_id"));


        SingleOutputStreamOperator<TradeOrderBean> tradeOrderDS =
                keyByDS.flatMap(new RichFlatMapFunction<JSONObject, TradeOrderBean>() {
            private ValueState<String> lastvaluestate;

            @Override
            public void open(Configuration parameters) throws Exception {
                //设置ttl
                StateTtlConfig stateTtlConfig =
                        new StateTtlConfig.Builder(Time.days(1)).setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite).build();
                //创建状态描述器
                ValueStateDescriptor<String> descriptor = new ValueStateDescriptor<>("laststate", String.class);
                //将配置作用于描述器
                descriptor.enableTimeToLive(stateTtlConfig);
                lastvaluestate = getRuntimeContext().getState(descriptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeOrderBean> out) throws Exception {
                //获取状态
                String lastdate = lastvaluestate.value();
                //获取日期
                Long createTime = DateFormatUtil.toTs(value.getString("create_time"), true);
                String curDt = DateFormatUtil.toDate(createTime);

                long orderUniqueUserCount = 0L;

                if (lastdate == null || !lastdate.equals(curDt)) {
                    orderUniqueUserCount = 1L;
                    lastvaluestate.update(curDt);
                    out.collect(new TradeOrderBean("", "", orderUniqueUserCount, null));
                }
            }
        });


        //TODO 6.开窗、聚合
        AllWindowedStream<TradeOrderBean, TimeWindow> windowAllDS =
                tradeOrderDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10L)));

        SingleOutputStreamOperator<TradeOrderBean> reduceDS = windowAllDS.reduce(new ReduceFunction<TradeOrderBean>() {
            @Override
            public TradeOrderBean reduce(TradeOrderBean value1, TradeOrderBean value2) throws Exception {
                value1.setOrderUniqueUserCount(value1.getOrderUniqueUserCount() + value2.getOrderUniqueUserCount());
                return value1;
            }
        }, new AllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow window, Iterable<TradeOrderBean> values, Collector<TradeOrderBean> out) throws Exception {
                //获取数据
                TradeOrderBean next = values.iterator().next();

                String sst = DateFormatUtil.toYmdHms(window.getStart());
                String edt = DateFormatUtil.toYmdHms(window.getEnd());

                //添加字段
                next.setEdt(edt);
                next.setStt(sst);
                next.setTs(System.currentTimeMillis());

                //写出数据
                out.collect(next);
            }
        });
        //TODO 7.将数据写入clickhouse
        reduceDS.print("===>");
        reduceDS.addSink(ClickHouseUtil.getJdbcSink("insert into dws_trade_order_window values(?,?,?,?)"));

        //TODO 8.执行任务
        env.execute("dws_trade_order_window");
    }
}
